package com.fashion.web.actions.management.news;

import com.fashion.exceptions.ColumnNotFoundException;
import com.fashion.exceptions.NewsNotFoundException;
import com.fashion.model.*;
import com.fashion.model.gallery.Photo;
import com.fashion.service.*;
import com.fashion.thread.RefreshNewsHtmlThread;
import com.fashion.utils.*;
import com.opensymphony.xwork2.ActionSupport;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
import java.util.regex.PatternSyntaxException;

/**
 * User: juventus
 * Date: 11-5-30
 * Time: 下午4:03
 */
@Scope("prototype")
@Controller
@Namespace("/management/news")
@ParentPackage("json-default")
public class NewsAction extends ActionSupport implements ServletRequestAware, SessionAware {
    private int page;
    private int rows;
    private Date publishFromDate;
    private Date publishToDate;
    private NewsService newsService;
    private VideoService videoService;
    private NewsSourceService newsSourceService;
    private CollectedNewsService collectedNewsService;

    private String jsonResult;
    private String id;
    private News news;
    private String columns;
    private int totalNumber;
    private String newsTitle;
    private String newsIndexTitle;
    private String newsColumn;
    private Map<String, Object> dataGridView;
    private String thumbNailFileName;
    private File thumbNail;
    private boolean operationSuccess;
    private GeneralResult newsResult;
    private Map<String, Object> session;
    private int indexLevel;
    private int inIndex;
    private String newsSourceTitle;
    private String collectedNewsTitle;
    private NewsSource newsSource;
    //Just to pass the value to ui
    private String columnIds;

    private String idString;
    private HttpServletRequest request;

    private NewsColumnItemService newsColumnItemService;
    @Resource(name = "columnService")
    private ColumnService columnService;
    private InLineWordService inLineWordService;

    private List<UrlKeyword> keywords = new ArrayList<UrlKeyword>();
    private String tag;
    private static final Logger logger = Logger.getLogger(NewsAction.class);

    private String columnUrl;
    private String topColumnUrl;

    //缩略图对象
    private Photo photo;

    private InLineWord inLineWordForm;
    private List<InLineWord> inLineWords;
    private InLineWordResult inLineWordResult;
    private String wordName;

    private String[] invalidWords = new String[]{"成人网", "加QQ", "加qq", "www.", ".com", ".net", ".cn", "where", "from",
            "insert", "select", "delete", "update", "alter", "drop", "?", "null", "草榴"};

    @Action(value = "index", results = {@Result(name = SUCCESS, location = "../../index/index.jsp")})
    public String index() throws Exception {
        logger.debug("in index action");

        List<NewsTemplate> templates = new ArrayList<NewsTemplate>();
        templates.add(new NewsTemplate(5, 6));

        List<News> indexNews = newsService.searchNewsByTemplateList(templates, 2);
        request.setAttribute("indexNews", indexNews);

        templates.clear();
        templates.add(new NewsTemplate(2, 9));
        templates.add(new NewsTemplate(3, 3));

        List<News> pictureNews = newsService.searchNewsByColumnAndTemplateList("图库", templates, 2);
        request.setAttribute("pictureNews", pictureNews);

        return SUCCESS;
    }

    @Action(value = "newsIndex", results = {@Result(name = SUCCESS, location = "../../index/news.index.jsp")})
    public String newsIndex() throws Exception {
        return SUCCESS;
    }

    @Action(value = "newsManagementIndex", results = {@Result(name = SUCCESS, location = "news_index.jsp")})
    public String newsManagementIndex() throws Exception {
        return SUCCESS;
    }

    @Action(value = "newsDraftIndex", results = {@Result(name = SUCCESS, location = "news_draft.jsp")})
    public String newsDraftIndex() throws Exception {
        return SUCCESS;
    }

    @Action(value = "fetchDraftNews", results = {@Result(name = SUCCESS, type = "json", params = {"root", "dataGridView"})})
    public String fetchDraftNews() throws Exception {
        List<News> newses = newsService.searchDraftNews(newsTitle, newsIndexTitle, newsColumn, inIndex, indexLevel, page, rows);
        int newsCount = newsService.countDraftNews(newsTitle, newsIndexTitle, newsColumn, inIndex, indexLevel);

        dataGridView = new HashMap<String, Object>();
        dataGridView.put("rows", newses);
        dataGridView.put("total", newsCount);

        return SUCCESS;
    }

    @Action(value = "fetchNews", results = {@Result(name = SUCCESS, type = "json", params = {"root", "dataGridView"})})
    public String fetchNews() throws Exception {
        Administrator author = (Administrator) session.get(ConstItem.USER_OBJECT_IN_SESSION);

        List<News> newses = newsService.searchNews(author, newsTitle, newsIndexTitle, newsColumn, inIndex, indexLevel, page, rows);
        int newsCount = newsService.countNews(author, newsTitle, newsIndexTitle, newsColumn, inIndex, indexLevel);

        dataGridView = new HashMap<String, Object>();
        dataGridView.put("rows", newses);
        dataGridView.put("total", newsCount);

        return SUCCESS;
    }

    @Action(value = "newsForm", results = {@Result(name = SUCCESS, location = "news_form.jsp")})
    public String newsForm() throws Exception {
        boolean isForDraft = false;

        if (StringUtils.isNullOrEmpty(id)) {
            news = new News();
            news.setId(StringUtils.createTimeStamp());
            news.setCreateDate(new Date());
            news.setPublishDate(new Date());
            logger.info("create news with id: " + news.getId());
            Administrator author = (Administrator) session.get(ConstItem.USER_OBJECT_IN_SESSION);
            news.setAuthor(author.getDisplayName());
            news.setCreatorId(author.getId());
            news.setBriefImage(ConstItem.DEFAULT_THUMBNAIL);
            news.setBriefImageVertical(false);
        } else {
            news = newsService.getNewsById(id);
            columnIds = createColumnIdString(newsColumnItemService.findNewsColumnItemsByNews(news));
            String videoId = news.getVideoId();
            if (!StringUtils.isNullOrEmpty(videoId)) {
                Video video = videoService.findVideoById(videoId);
                request.setAttribute("video", video);
            }

            isForDraft = Boolean.parseBoolean(request.getParameter("isForDraft"));
            logger.info("edit news with id: " + news.getId());
        }

        request.setAttribute("isForDraft", isForDraft);

        return SUCCESS;
    }

    //  @Action(value = "newsSaveOrUpdate", results = {@Result(name = SUCCESS, location = "newsIndex.action", type = "redirectAction")})
    @Action(value = "newsSaveOrUpdate", results = {@Result(name = SUCCESS, location = "../../form_result.jsp")})
    public String newsSaveOrUpdate() throws Exception {
        try {
            String context = news.getContext();
            String pagedContext = context.replaceAll(NewsService.PageSplitterReg, NewsService.PageSplitter);
            news.setContext(pagedContext);
            newsService.saveOrUpdate(news);

            //新闻和栏目关联
            if (columns != null) {
                String[] columnIds = columns.split(",");
                newsService.handleColumnsForNews(news, Arrays.asList(columnIds));
            }

            jsonResult = "true";

            if (news.isPublished()) {
                StringBuilder urlPrefixBuilder = fetchUrlPrefixBuilder();

                String urlPrefix = urlPrefixBuilder.toString();
                String url = urlPrefixBuilder.append("/n-").append(news.getId()).append(".html").toString();
                newsService.saveHtmlNews(url, urlPrefix, ServletActionContext.getServletContext().getRealPath(StringUtils.Persistent_Html_Folder));
            }

            String collectedNewsId = request.getParameter("collectedNewsId");
            if (!StringUtils.isNullOrEmpty(collectedNewsId)) {
                collectedNewsService.deleteEntityById(collectedNewsId);
            }
        } catch (Exception e) {
            logger.error("Failed to save news: " + news.getTitle(),e);
        }

        return SUCCESS;
    }

    //bulkApproveNews
    @Action(value = "bulkApproveNews", results = {@Result(name = SUCCESS, type = "json", params = {"root", "newsResult"})})
    public String bulkApproveNews() throws Exception {
        newsResult = new GeneralResult();

        try {
            String ids = request.getParameter("ids");

            for (String id : StringUtils.splitToList(ids, "_")) {
                News news = newsService.getNewsById(id);
                news.setPublished(true);
                newsService.saveOrUpdate(news);
            }
            newsResult.setSuccessful(true);
        } catch (Exception e) {
            logger.error("error in bulk approve news!", e);
            newsResult.setSuccessful(false);
            newsResult.setErrorMessage(e.getMessage());
        }

        return SUCCESS;
    }

    @Action(value = "deleteNews", results = {@Result(name = SUCCESS, type = "json", params = {"root", "newsResult"})})
    public String deleteNews() throws Exception {
        newsResult = new GeneralResult();
        Administrator author = (Administrator) session.get(ConstItem.USER_OBJECT_IN_SESSION);

        if (null == author) {
            newsResult.setSuccessful(false);
            newsResult.setErrorMessage("No user logged in!");

            return SUCCESS;
        }

        try {
            List<NewsColumnItem> newsColumnItems = newsService.findColumnItemsByNewsId(id);
            List<String> itemIds = new ArrayList<String>();

            for (NewsColumnItem newsColumnItem : newsColumnItems) {
                itemIds.add(newsColumnItem.getId());
            }

            newsService.bulkDeleteNewsColumnItems(itemIds);
            newsService.deleteEntityById(id);
            newsService.deleteHtmlNews(id, ServletActionContext.getServletContext().getRealPath(StringUtils.Persistent_Html_Folder));

            newsResult.setSuccessful(true);
        } catch (Exception e) {
            logger.error("Exception in delete news with id: " + id, e);
            newsResult.setSuccessful(false);
            newsResult.setErrorMessage(e.getMessage());
        }

        return SUCCESS;
    }

    @Action(value = "copyNews", results = {@Result(name = SUCCESS, type = "json", params = {"root", "newsResult"})})
    public String copyNews() throws Exception {
        newsResult = new GeneralResult();
        Administrator author = (Administrator) session.get(ConstItem.USER_OBJECT_IN_SESSION);

        if (null == author || author.getRole() != 1 ) {
            newsResult.setSuccessful(false);
            newsResult.setErrorMessage("No valid user logged in!");

            return SUCCESS;
        }

        try {
            News oldNews = newsService.getNewsById(id);
            int number = Integer.valueOf(request.getParameter("number"));
            if(number < 1){
                number = 1;
            }

            for (int i = 0; i < number; i++) {
                List<NewsColumnItem> items = newsColumnItemService.findNewsColumnItemsByNews(oldNews);
                copySingleNews(oldNews,items, i);
            }

            newsResult.setSuccessful(true);
            newsResult.setServerMessage("Operation successfully done!");
        } catch (Exception e) {
            logger.error("Exception in copy news with id: " + id, e);
            newsResult.setSuccessful(false);
            newsResult.setErrorMessage(e.getMessage());
        }

        return SUCCESS;
    }

    private void copySingleNews(News oldNews, List<NewsColumnItem> items, int index) {
        String newsId = StringUtils.createTimeStamp();
        News copiedNews = new News();
        copiedNews.setId(newsId);
        copiedNews.setCreateDate(new Date());
        copiedNews.setPublishDate(new Date());
        copiedNews.setAuthor(oldNews.getAuthor());
        copiedNews.setBriefImage(oldNews.getBriefImage());
        copiedNews.setBriefImageTitle(oldNews.getBriefImageTitle());
        copiedNews.setBriefImageVertical(oldNews.isBriefImageVertical());
        copiedNews.setContext(oldNews.getContext());
        copiedNews.setCreatorId(oldNews.getCreatorId());
        copiedNews.setHasComment(oldNews.isHasComment());
        copiedNews.setIndexFinishDate(oldNews.getIndexFinishDate());
        copiedNews.setSeoTitle(oldNews.getSeoTitle());
        copiedNews.setMetaData(oldNews.getMetaData());
        copiedNews.setIndexLevel(oldNews.getIndexLevel());
        copiedNews.setInIndex(oldNews.getInIndex());
        copiedNews.setIndexStartDate(oldNews.getIndexStartDate());
        copiedNews.setKeywords(oldNews.getKeywords());
        copiedNews.setAuthor(oldNews.getAuthor());
        copiedNews.setRedirect(oldNews.getRedirect());
        copiedNews.setSource(oldNews.getSource());
        copiedNews.setSourceUrl(oldNews.getSourceUrl());
        copiedNews.setSuggest(oldNews.isSuggest());
        copiedNews.setViceTitle(oldNews.getViceTitle());
        copiedNews.setViceTitlePosition(oldNews.getViceTitlePosition());
        copiedNews.setVideoId(oldNews.getVideoId());
        copiedNews.setViewTimes(oldNews.getViewTimes());
        copiedNews.setPublished(oldNews.isPublished());
        copiedNews.setTitle(index + oldNews.getTitle());
        copiedNews.setIndexTitle(index + oldNews.getIndexTitle());

        newsService.saveOrUpdate(copiedNews);

        for (NewsColumnItem item : items) {
            NewsColumnItem newsColumnItem = new NewsColumnItem();
            newsColumnItem.setId(StringUtils.createGuid());
            newsColumnItem.setNewsId(newsId);
            newsColumnItem.setColumnId(item.getColumnId());

            newsColumnItemService.saveOrUpdate(newsColumnItem);
        }
    }


    @Action(value = "showNews", results = {@Result(name = SUCCESS, location = "news_show.jsp"),
            @Result(name = "fashion", location = "news_show_fashion.jsp"),
            @Result(name = "pic", location = "news_show_pic.jsp"),
            @Result(name = "luxury", location = "news_show_luxury.jsp"),
            @Result(name = "people", location = "news_show_people.jsp"),
            @Result(name = "life", location = "news_show_life.jsp"),
            @Result(name = "news", location = "news_show.jsp"),
            @Result(name = ERROR, location = "../../error.jsp")
    })
    public String showNews() throws Exception {
        try {
            Administrator administrator = (Administrator) session.get(ConstItem.USER_OBJECT_IN_SESSION);

            if (id.contains("-")) {
                String[] parameters = id.split("-");
                id = parameters[0];
                page = StringUtils.parseStringToInt(parameters[1]);
            }

            long start = System.currentTimeMillis();
            news = newsService.getNewsById(id);

            if (null != administrator && "fashion".equalsIgnoreCase(administrator.getName())) {
                logger.info("in showNews time for load news: " + (System.currentTimeMillis() - start));
            }

            String context = news.getContext();
            //    context = StringUtils.replaceWithRegex(NewsService.OldPageSplitterReg,context, NewsService.PageSplitter);
            String[] pageContexts = context.split(NewsService.PageSplitter);
            totalNumber = pageContexts.length;
            if (page < 1) {
                page = 1;
            }

            if (page > totalNumber) {
                page = totalNumber;
            }

            int nextPage = page + 1;
            if (nextPage > totalNumber) {
                nextPage = 1;
            }

            int lastPage = calculateLastPage(page, totalNumber);
            int startPage = calculateStartPage(page, totalNumber);

            String pageContext = pageContexts[page - 1];
            //Start inline
            List<InLineWord> inLineWords = inLineWordService.searchInLineWords("", 1, 280);

            for (InLineWord inLineWord : inLineWords) {
                try {
                    pageContext = StringUtils.addInline(pageContext, inLineWord);
                }catch (PatternSyntaxException ex){
                    logger.error("PatternSyntaxException in showNews()-->addInline(), should fix it later",ex);
                }catch (Exception e) {
                    logger.error("Unexpected error in addInline",e);
                }
            }

            news.setContext(pageContext);
            String pageTitle = news.getTitle();

            /*   if (page > 1) {
                String firstImageAlt = HtmlUtils.fetchFirstAttribute(pageContext, "img", "alt");
                if (!StringUtils.isNullOrEmpty(firstImageAlt)) {
                    pageTitle = firstImageAlt;
                }
            }*/

            request.setAttribute("pageTitle", pageTitle);

            List<News> suggestNewsList = newsService.searchSuggestNews("", "", 1, 12);

            List<NewsColumn> columnList = columnService.findNewsColumnsByNews(news);
            NewsColumn column = columnList.get(0);
            NewsColumn topColumn = columnService.findTopColumn(column);
            List<NewsColumn> columnUrlPaths = columnService.findUrlForPathColumn(column);

            request.setAttribute("topColumn", topColumn);
            request.setAttribute("columnUrlPaths", columnUrlPaths);

            List<News> mostViewedNewsList = newsService.searchMostViewedNewsByColumn(column.getId(), 1, 10);

            request.setAttribute("suggestNewsList", suggestNewsList);
            request.setAttribute("newsColumn", column);
            request.setAttribute("mostViewedNewsList", mostViewedNewsList);
            request.setAttribute("nextPage", nextPage);
            request.setAttribute("lastPage", lastPage);
            request.setAttribute("startPage", startPage);

            //专题回顾
            start = System.currentTimeMillis();
            List<News> specialNews = findSpecialNews();
            //   newsService.formatNewsTitle(specialNews, 16);
            if (null != administrator && "fashion".equalsIgnoreCase(administrator.getName())) {
                logger.info("in showNews time for specialNews: " + (System.currentTimeMillis() - start));
            }

            request.setAttribute("specialNewsList", specialNews);

            //video
          /*  String videoId = news.getVideoId();
            if (!StringUtils.isNullOrEmpty(videoId)) {
                Video video = videoService.findVideoById(videoId);
                request.setAttribute("video", video);
            }*/

            String newsKeywords = news.getKeywords();
            request.setAttribute("newsKeywords", newsKeywords.replace("$", " "));
            List<String> rawKeywords = StringUtils.splitToList(newsKeywords, " ");

            for (String keyword : rawKeywords) {
                String keywordWithoutSpace = keyword.replace("$", " ");
                /*keywords.add(new UrlKeyword(keywordWithoutSpace, URLEncoder.encode(keywordWithoutSpace, "UTF-8")));*/
                keywords.add(StringUtils.makeUrlKeyword(keywordWithoutSpace));
            }

            start = System.currentTimeMillis();
            List<News> aboutNewsList = newsService.searchAboutNewsByKeywordsList(rawKeywords, news.getId());
            long aboutListTime = System.currentTimeMillis() - start;
            if (aboutListTime > 500) {
                logger.info("long time for aboutNewsList: " + aboutListTime + " and the news id is: " + news.getId());
            }

            request.setAttribute("aboutNewsList", aboutNewsList);

            String topColumnUrl = topColumn.getUrl();
            if("people".equals(topColumnUrl)) {
                return "people";
            }else if("fashion".equals(topColumnUrl)){
                return "fashion";
            }else if("pic".equals(topColumnUrl)){
                return "pic";
            }else if("luxury".equals(topColumnUrl)){
                return "luxury";
            }else if("life".equals(topColumnUrl)){
                return "life";
            }else if("news".equals(topColumnUrl)){
                return "news";
            }

            return SUCCESS;

        } catch (NullPointerException ex) {
            logger.debug("NullPointerException in showNews No News with id: " + id);

            return ERROR;
        } catch (IndexOutOfBoundsException ex) {
            logger.debug("IndexOutOfBoundsException in showNews No column for News with id: " + id + " news should be deleted or attached to a column");

            return ERROR;
        } catch (NewsNotFoundException e) {
            logger.debug("News not found for id: " + id, e);

            return ERROR;
        } catch (Exception e) {
            String originalURL = (String) request.getAttribute("originalURL");
            String mappedURL = (String) request.getAttribute("mappedURL");

            logger.error("exception in show news for " + mappedURL + " the original URL is: " + originalURL, e);
            return ERROR;
        }
    }

    @Action(value = "showNewsBackend", results = {@Result(name = SUCCESS, location = "news_show_backend.jsp"), @Result(name = ERROR, location = "../../error.jsp")})
    public String showNewsBackend() throws Exception {
        logger.debug("in showNewsBackend()");
        String result = showNews();

        if(ERROR.equalsIgnoreCase(result)){
            return ERROR;
        }

        return SUCCESS;
    }

    @Action(value = "addNewsViewTime", results = {@Result(name = SUCCESS, type = "json", params = {"root", "newsResult"})})
    public String addNewsViewTime() throws Exception {
        newsResult = new GeneralResult();
        try {
            news = newsService.getNewsById(id);
            news.setViewTimes(news.getViewTimes() + 1);
            newsService.saveOrUpdate(news);

            newsResult.setSuccessful(true);
        } catch (IllegalArgumentException ie) {
            logger.debug("no news with id: " + id);
        } catch (NullPointerException npe) {
            logger.debug("no news with id: " + id);
        } catch (Exception e) {
            logger.error("Exception in add view time for news with id: " + id, e);
            newsResult.setSuccessful(false);
            newsResult.setErrorMessage(e.getMessage());
        }

        return SUCCESS;
    }

    @Action(value = "previewNews", results = {@Result(name = SUCCESS, location = "news_preview.jsp")})
    public String previewNews() throws Exception {
        String formattedContext = formatNewsContext(news.getContext());
        news.setContext(formattedContext);

        String[] pageContexts = formattedContext.split(NewsService.PageSplitter);
        totalNumber = pageContexts.length;

        if (page < 1) {
            page = 1;
        }

        if (page > totalNumber) {
            page = totalNumber;
        }

        int nextPage = page + 1;
        if (nextPage > totalNumber) {
            nextPage = 1;
        }

        int lastPage = calculateLastPage(page, totalNumber);
        int startPage = calculateStartPage(page, totalNumber);

        news.setContext(pageContexts[page - 1]);
        List<News> suggestNewsList = newsService.searchSuggestNews("", "", 1, 8);
        request.setAttribute("suggestNewsList", suggestNewsList);
        //专题回顾
        List<News> specialNews = findSpecialNews();
        //  newsService.formatNewsTitle(specialNews, 16);
        request.setAttribute("specialNewsList", specialNews);
        request.setAttribute("formattedContext", formattedContext);

        List<String> rawKeywords = StringUtils.splitToList(news.getKeywords(), " ");
        for (String keyword : rawKeywords) {
            String keywordWithoutSpace = keyword.replace("$", " ");
            keywords.add(new UrlKeyword(keywordWithoutSpace, URLEncoder.encode(keywordWithoutSpace, "UTF-8")));
        }

        request.setAttribute("nextPage", nextPage);
        request.setAttribute("lastPage", lastPage);
        request.setAttribute("startPage", startPage);

        return SUCCESS;
    }

    @Action(value = "aboutNews", results = {@Result(name = SUCCESS, location = "about_news_index.jsp")})
    public String aboutNews() throws Exception {
        news = newsService.getNewsById(id);

        return SUCCESS;
    }

    @Action(value = "fetchAboutNews", results = {@Result(name = SUCCESS, type = "json", params = {"root", "dataGridView"})})
    public String fetchAboutNews() throws Exception {
        List<News> aboutNewsList = newsService.searchAboutNews(id, page, rows);
        int aboutNewsCount = newsService.countAboutNews(id);

        dataGridView = new HashMap<String, Object>();
        dataGridView.put("rows", aboutNewsList);
        dataGridView.put("total", aboutNewsCount);

        return SUCCESS;
    }

    @Action(value = "fetchNonAboutNews", results = {@Result(name = SUCCESS, type = "json", params = {"root", "dataGridView"})})
    public String fetchNonAboutNews() throws Exception {
        List<News> nonAboutNewsList = newsService.searchNonAboutNews(id, newsTitle, newsColumn, page, rows);
        int nonAboutNewsCount = newsService.countNonAboutNews(id, newsTitle, newsColumn);

        dataGridView = new HashMap<String, Object>();
        dataGridView.put("rows", nonAboutNewsList);
        dataGridView.put("total", nonAboutNewsCount);

        return SUCCESS;
    }

    @Action(value = "addAboutNews", results = {@Result(name = SUCCESS, location = "../../form_result.jsp")})
    public String addAboutNews() throws Exception {
        String[] targetNewsIds = idString.split(",");

        for (String targetNewsId : targetNewsIds) {
            newsService.addAboutNews(id, targetNewsId);
        }

        jsonResult = "true";
        return SUCCESS;
    }

    @Action(value = "deleteAboutNews", results = {@Result(name = SUCCESS, location = "../../form_result.jsp")})
    public String deleteAboutNews() throws Exception {
        String[] targetNewsIds = idString.split(",");

        for (String targetNewsId : targetNewsIds) {
            newsService.deleteAboutNews(id, targetNewsId);
        }

        jsonResult = "true";
        return SUCCESS;
    }

    @Action(value = "manageTopNews", results = {@Result(name = SUCCESS, location = "top_news_index.jsp")})
    public String manageTopNews() throws Exception {
        return SUCCESS;
    }

    @Action(value = "inLineNews", results = {@Result(name = SUCCESS, location = "inline_news_index.jsp")})
    public String inLineNews() throws Exception {
        return SUCCESS;
    }

    @Action(value = "fetchSuggestNews", results = {@Result(name = SUCCESS, type = "json", params = {"root", "dataGridView"})})
    public String fetchSuggestNews() throws Exception {
        List<News> topNewsList = newsService.searchSuggestNews(newsTitle, newsColumn, page, rows);
        int newsCount = newsService.countSuggestNews(newsTitle, newsColumn);
        dataGridView = new HashMap<String, Object>();
        dataGridView.put("rows", topNewsList);
        dataGridView.put("total", newsCount);

        return SUCCESS;
    }

    @Action(value = "fetchNonSuggestNews", results = {@Result(name = SUCCESS, type = "json", params = {"root", "dataGridView"})})
    public String fetchNonSuggestNews() throws Exception {
        List<News> topNewsList = newsService.searchNonSuggestNews(newsTitle, newsColumn, page, rows);
        int newsCount = newsService.countNonSuggestNews(newsTitle, newsColumn);
        dataGridView = new HashMap<String, Object>();
        dataGridView.put("rows", topNewsList);
        dataGridView.put("total", newsCount);

        return SUCCESS;
    }

    @Action(value = "addSuggestNews", results = {@Result(name = SUCCESS, location = "../../form_result.jsp")})
    public String addSuggestNews() throws Exception {
        String[] targetNewsIds = idString.split(",");

        for (String targetNewsId : targetNewsIds) {
            newsService.addSuggestNews(targetNewsId);
        }

        jsonResult = "true";
        return SUCCESS;
    }

    @Action(value = "deleteSuggestNews", results = {@Result(name = SUCCESS, location = "../../form_result.jsp")})
    public String deleteSuggestNews() throws Exception {
        String[] targetNewsIds = idString.split(",");
        newsService.deleteSuggestNews(targetNewsIds);

        jsonResult = "true";
        return SUCCESS;
    }

    @Action(value = "addThumbnailForNews", results = {@Result(name = SUCCESS, type = "json", params = {
            "root", "photo"})})
    public String addThumbnailForNews() throws Exception {
        try {
            String nowTime = StringUtils.createTimeStamp();
            String preFolder = StringUtils.generateNameByYearAndMonth();
            String saveName = nowTime + "-" + thumbNailFileName;
            //   String saveName = nowTime + StringUtils.findSuffixName(thumbNailFileName);
            String folder = ServletActionContext.getServletContext().getRealPath("/thumbnail/") + File.separator + preFolder;
            newsService.saveThumbNail(thumbNail, folder, saveName);
            photo = new Photo();
            photo.setName(preFolder + "/" + saveName);
            photo.setVertical(newsService.checkVerticalImage(thumbNail));
        } catch (IOException e) {
            LOG.error("Exception in setting thumbnail: " + thumbNailFileName, e);
            throw new RuntimeException(e);
        }

        return SUCCESS;
    }

    //通过关键字搜索新闻
    @Action(value = "searchTagNews", results = {@Result(name = SUCCESS, location = "tag_news.jsp"), @Result(name = ERROR, location = "../../error.jsp")})
    public String searchTagNews() throws Exception {
        String rawEncodedTagName = (String) request.getAttribute("encodedTagName");

        if (StringUtils.isNullOrEmpty(rawEncodedTagName)) {
            logger.error("Tag " + rawEncodedTagName + " is null or empty!");
            return ERROR;
        }

        for (String invalidWord : invalidWords) {
            if (rawEncodedTagName.toLowerCase().contains(invalidWord)) {
                logger.error("Tag " + rawEncodedTagName + " contains invalid word " + invalidWord);
                return ERROR;
            }
        }

        try {
            String encodedTagName = StringUtils.removeSlash(rawEncodedTagName);

            if (rawEncodedTagName.contains("_")) {
                String[] parameters = rawEncodedTagName.split("_");
                encodedTagName = parameters[0];
                page = StringUtils.parseStringToInt(parameters[1]);
            }

            if (page < 1) {
                page = 1;
            }

            tag = URLDecoder.decode(encodedTagName, "GB2312");

            request.setAttribute("encodedTagName", encodedTagName);

            tag = tag.replace(" ", "$");

            if (StringUtils.isNullOrEmpty(tag)) {
                logger.debug("Tag is null or empty");
                return ERROR;
            }
            for (String invalidWord : invalidWords) {
                if (tag.toLowerCase().contains(invalidWord)) {
                    logger.debug("Tag contains invalid word " + invalidWord);
                    return ERROR;
                }
            }

            totalNumber = newsService.countTagNews(tag);
            if (totalNumber == 0) {
                logger.error("No news for tag: " + rawEncodedTagName);
                return ERROR;
            }

            int pageNumber = ManagementUtils.calculatePageNumber(totalNumber, 10);

            if (page > pageNumber) {
                page = 1;
            }

            int lastPage = calculateLastPage(page, pageNumber);
            int startPage = calculateStartPage(page, pageNumber);

            List<News> tagNewsList = newsService.searchTagNews(tag, page, 10);

            tag = tag.replace("$", " ");

            List<News> suggestNewsList = newsService.searchSuggestNews("", "", 1, 8);
            List<News> mostViewedNewsList = newsService.searchMostViewedNews(1, 10);

            request.setAttribute("suggestNewsList", suggestNewsList);
            request.setAttribute("mostViewedNewsList", mostViewedNewsList);
            request.setAttribute("tagNewsList", tagNewsList);
            request.setAttribute("pageNumber", pageNumber);
            request.setAttribute("lastPage", lastPage);
            request.setAttribute("startPage", startPage);

            return SUCCESS;
        } catch (Exception e) {
            logger.error("error in tag news for: " + rawEncodedTagName, e);
            return ERROR;
        }
    }

    @Action(value = "fetchInLineWords", results = {@Result(name = SUCCESS, type = "json", params = {"root", "dataGridView"})})
    public String fetchInLineWords() throws Exception {
        List<InLineWord> inLineWords = inLineWordService.searchInLineWords(wordName, page, rows);
        int inLineWordsCount = inLineWordService.countInLineWords(wordName);
        dataGridView = new HashMap<String, Object>();
        dataGridView.put("rows", inLineWords);
        dataGridView.put("total", inLineWordsCount);

        return SUCCESS;
    }

    protected int calculateStartPage(int currentPage, int totalPage) {
        if (totalPage < 11) {
            return 1;
        }

        if ((currentPage + 9) <= totalPage) {
            return currentPage;
        }

        if ((totalPage - 9) > 0) {
            return (totalPage - 9);
        }

        return currentPage;
    }

    protected int calculateLastPage(int currentPage, int totalPage) {
        if (totalPage - currentPage > 10) {
            return (currentPage + 9);
        }

        return totalPage;
    }

    //搜索频道新闻
    @Action(value = "searchColumnNews", results = {@Result(name = SUCCESS, location = "column_news.jsp"), @Result(name = ERROR, location = "../../error.jsp")})
    public String searchColumnNews() throws Exception {
        try {
            Administrator author = (Administrator) session.get(ConstItem.USER_OBJECT_IN_SESSION);
            if (columnUrl.contains("_")) {
                String[] parameters = columnUrl.split("_");
                page = StringUtils.parseStringToInt(parameters[1]);
                columnUrl = parameters[0];
            }

            if (page < 1) {
                page = 1;
            }

            columnUrl = StringUtils.removeSlash(columnUrl);

            long start = System.currentTimeMillis();
            NewsColumn column = columnService.findColumnByUrl(topColumnUrl, columnUrl);
            if (null != author && "fashion".equalsIgnoreCase(author.getName())) {
                logger.info("in searchColumnNews time for findColumnByUrl: " + (System.currentTimeMillis() - start));
            }

            List<NewsColumn> columns = new ArrayList<NewsColumn>();
            columns.add(column);
            columns.addAll(columnService.getAllChildren(column));

            start = System.currentTimeMillis();
            totalNumber = newsService.countNewsByColumns(columns);
            if (null != author && "fashion".equalsIgnoreCase(author.getName())) {
                logger.info("in searchColumnNews time for countNewsByColumns: " + (System.currentTimeMillis() - start));
            }

            int pageNumber = ManagementUtils.calculatePageNumber(totalNumber, 10);

            if (page > pageNumber) {
                page = 1;
            }

            int lastPage = calculateLastPage(page, pageNumber);
            int startPage = calculateStartPage(page, pageNumber);

            start = System.currentTimeMillis();
            List<News> columnNewsList = newsService.searchNewsByColumns(columns, page, 10);
            if (null != author && "fashion".equalsIgnoreCase(author.getName())) {
                logger.info("in searchColumnNews time for searchNewsByColumns: " + (System.currentTimeMillis() - start));
            }

            start = System.currentTimeMillis();
            List<News> topNewsList = newsService.searchSuggestNews("", "", 1, 8);
            if (null != author && "fashion".equalsIgnoreCase(author.getName())) {
                logger.info("in searchColumnNews time for searchSuggestNews: " + (System.currentTimeMillis() - start));
            }

            start = System.currentTimeMillis();
            List<News> mostViewedNewsList = newsService.searchMostViewedNews(1, 10);
            if (null != author && "fashion".equalsIgnoreCase(author.getName())) {
                logger.info("in searchColumnNews time for searchMostViewedNews: " + (System.currentTimeMillis() - start));
            }

            request.setAttribute("topNewsList", topNewsList);
            request.setAttribute("mostViewedNewsList", mostViewedNewsList);
            request.setAttribute("columnNewsList", columnNewsList);
            request.setAttribute("pageNumber", pageNumber);
            request.setAttribute("columnName", column.getName());
            request.setAttribute("column", column);
            request.setAttribute("lastPage", lastPage);
            request.setAttribute("startPage", startPage);

            //专题回顾
            List<News> specialNews = findSpecialNews();
            //   newsService.formatNewsTitle(specialNews, 16);
            request.setAttribute("specialNewsList", specialNews);

            return SUCCESS;
        } catch (ColumnNotFoundException ex) {
            String originalURL = (String) request.getAttribute("originalURL");
            String mappedURL = (String) request.getAttribute("mappedURL");

            //  logger.error(ex.getMessage());
            // logger.error("no column for " + mappedURL + " the original URL is: " + originalURL);

            return ERROR;
        } catch (Exception e) {
            String originalURL = (String) request.getAttribute("originalURL");
            String mappedURL = (String) request.getAttribute("mappedURL");

            logger.error("exception in search column news for " + mappedURL + " the original URL is: " + originalURL, e);
            return ERROR;
        }
    }

    @Action(value = "deleteInLineWord", results = {@Result(name = SUCCESS, type = "json", params = {"root", "inLineWordResult"})})
    public String deleteInLineWord() throws Exception {
        inLineWordResult = new InLineWordResult();

        try {
            inLineWordService.deleteEntityById(id);
            inLineWordResult.setSuccessful(true);
        } catch (Exception e) {
            logger.error("Exception in delete news with id: " + id, e);
            inLineWordResult.setSuccessful(false);
            inLineWordResult.setErrorMessage(e.getMessage());
        }

        return SUCCESS;
    }

    @Action(value = "inLineWordForm", results = {@Result(name = SUCCESS, location = "../../form_result.jsp")})
    public String inLineWordForm() throws Exception {
        boolean duplicated = false;
        inLineWordResult = new InLineWordResult();
        List<InLineWord> savedInLineWords = inLineWordService.loadAllWords();

        String word = inLineWordForm.getWord().trim();
        inLineWordForm.setWord(word);
        String id = inLineWordForm.getId();
        for (InLineWord savedInLineWord : savedInLineWords) {
            String savedWord = savedInLineWord.getWord();
            String wordId = savedInLineWord.getId();
            if (savedWord.equalsIgnoreCase(word) && !wordId.equals(id)) {
                inLineWordResult.setSuccessful(false);
                inLineWordResult.setErrorMessage("已有相同的内联存在！");
                duplicated = true;
                break;
            }
        }

        if (!duplicated) {
            if (StringUtils.isNullOrEmpty(id)) {
                inLineWordForm.setId(StringUtils.createTimeStamp());
                inLineWordForm.setCreateDate(new Date());
                inLineWordResult.setEdit(false);
            } else {
                inLineWordResult.setEdit(true);
            }

            inLineWordService.saveOrUpdate(inLineWordForm);
            inLineWordResult.setSuccessful(true);
        }

        inLineWords = new ArrayList<InLineWord>();
        inLineWords.add(inLineWordForm);
        inLineWordResult.setInLineWords(inLineWords);

        JSONObject jsonObject = JSONObject.fromObject(inLineWordResult);
        jsonResult = jsonObject.toString();

        return SUCCESS;
    }

    @Action(value = "saveNewsToHtml", results = {@Result(name = SUCCESS, type = "json", params = {"root", "newsResult"})})
    public String saveNewsToHtml() throws Exception {
        newsResult = new GeneralResult();
        Administrator administrator = (Administrator) session.get(ConstItem.USER_OBJECT_IN_SESSION);

        if (null == administrator) {
            newsResult.setSuccessful(false);
            newsResult.setErrorMessage("No administrator logged in!");

            return SUCCESS;
        }

        if (1 != administrator.getRole()) {
            newsResult.setSuccessful(false);
            newsResult.setErrorMessage("No administrator logged in!");

            return SUCCESS;
        }

        String id = request.getParameter("id");

        News newsToSave = newsService.getNewsById(id);
        if (!newsToSave.isPublished()) {
            newsResult.setSuccessful(false);
            newsResult.setErrorMessage("News not published!");
            return SUCCESS;
        }

        StringBuilder urlPrefixBuilder = fetchUrlPrefixBuilder();

        String urlPrefix = urlPrefixBuilder.toString();
        String url = urlPrefixBuilder.append("/n-").append(id).append(".html").toString();

        try {
            newsService.saveHtmlNews(url, urlPrefix, ServletActionContext.getServletContext().getRealPath(StringUtils.Persistent_Html_Folder));
            newsResult.setSuccessful(true);
        } catch (Exception e) {
            logger.error("failed to save html news: " + url, e);
            newsResult.setErrorMessage(e.getMessage());
            newsResult.setSuccessful(false);
        }

        return SUCCESS;
    }

    @Action(value = "deleteHtml", results = {@Result(name = SUCCESS, type = "json", params = {"root", "newsResult"})})
    public String deleteHtml() throws Exception {
        newsResult = new GeneralResult();
        Administrator administrator = (Administrator) session.get(ConstItem.USER_OBJECT_IN_SESSION);

        if (null == administrator) {
            newsResult.setSuccessful(false);
            newsResult.setErrorMessage("No administrator logged in!");

            return SUCCESS;
        }

        if (1 != administrator.getRole()) {
            newsResult.setSuccessful(false);
            newsResult.setErrorMessage("No administrator logged in!");

            return SUCCESS;
        }

        String id = request.getParameter("id");
        try {
            newsService.deleteHtmlNews(id, ServletActionContext.getServletContext().getRealPath(StringUtils.Persistent_Html_Folder));
            newsResult.setSuccessful(true);
        } catch (Exception e) {
            logger.error("failed to delete html news: " + id, e);
            newsResult.setErrorMessage(e.getMessage());
            newsResult.setSuccessful(false);
        }

        return SUCCESS;
    }

    @Action(value = "video", results = {@Result(name = SUCCESS, location = "video_index.jsp")})
    public String video() throws Exception {
        return SUCCESS;
    }

    @Action(value = "collectedNewsIndex", results = {@Result(name = SUCCESS, location = "collected_news_index.jsp")})
    public String collectedNewsIndex() throws Exception {
        return SUCCESS;
    }

    @Action(value = "deleteCollectedNews", results = {@Result(name = SUCCESS, type = "json", params = {"root", "newsResult"})})
    public String deleteCollectedNews() throws Exception {
        newsResult = new GeneralResult();
        Administrator author = (Administrator) session.get(ConstItem.USER_OBJECT_IN_SESSION);

        if (null == author) {
            newsResult.setSuccessful(false);
            newsResult.setErrorMessage("No user logged in!");

            return SUCCESS;
        }

        try {
            collectedNewsService.deleteEntityById(id);

            newsResult.setSuccessful(true);
        } catch (Exception e) {
            logger.error("Exception in delete collected news with id: " + id, e);
            newsResult.setSuccessful(false);
            newsResult.setErrorMessage(e.getMessage());
        }

        return SUCCESS;
    }


    //Be careful
    @Action(value = "deleteAllCollectedNews", results = {@Result(name = SUCCESS, type = "json", params = {"root", "newsResult"})})
    public String deleteAllCollectedNews() throws Exception {
        newsResult = new GeneralResult();
        Administrator author = (Administrator) session.get(ConstItem.USER_OBJECT_IN_SESSION);

        if (null == author) {
            newsResult.setSuccessful(false);
            newsResult.setErrorMessage("No user logged in!");

            return SUCCESS;
        }

        try {
            collectedNewsService.deleteAllCollectedNews();

            newsResult.setSuccessful(true);
        } catch (Exception e) {
            logger.error("Exception in delete collected news with id: " + id, e);
            newsResult.setSuccessful(false);
            newsResult.setErrorMessage(e.getMessage());
        }

        return SUCCESS;
    }

    @Action(value = "newsSourceIndex", results = {@Result(name = SUCCESS, location = "news_source_index.jsp")})
    public String newsSourceIndex() throws Exception {
        return SUCCESS;
    }

    @Action(value = "fetchNewsSource", results = {@Result(name = SUCCESS, type = "json", params = {"root", "dataGridView"})})
    public String fetchNewsSource() throws Exception {
        List<NewsSource> newsSourceList = null;
        int newsSourceCount = 0;
        try {
            newsSourceList = newsSourceService.searchNewsSource(newsSourceTitle, page, rows);
            newsSourceCount = newsSourceService.countNewsSource(newsSourceTitle);
        } catch (Exception e) {
            logger.error("error in fetchNewsSource", e);
        }

        dataGridView = new HashMap<String, Object>();
        dataGridView.put("rows", newsSourceList);
        dataGridView.put("total", newsSourceCount);

        return SUCCESS;
    }

    @Action(value = "newsSourceForm", results = {@Result(name = SUCCESS, location = "news_source_form.jsp")})
    public String newsSourceForm() throws Exception {
        if (StringUtils.isNullOrEmpty(id)) {
            newsSource = new NewsSource();
            newsSource.setId(StringUtils.createTimeStamp());
            newsSource.setLastUpdate(new Date());
        } else {
            newsSource = newsSourceService.getNewsSourceById(id);
        }

        return SUCCESS;
    }

    @Action(value = "newsSourceSaveOrUpdate", results = {@Result(name = SUCCESS, location = "../../form_result.jsp")})
    public String newsSourceSaveOrUpdate() throws Exception {
        newsSourceService.saveOrUpdate(newsSource);

        return SUCCESS;
    }

    @Action(value = "deleteNewsSource", results = {@Result(name = SUCCESS, type = "json", params = {"root", "newsResult"})})
    public String deleteNewsSource() throws Exception {
        newsResult = new GeneralResult();
        Administrator author = (Administrator) session.get(ConstItem.USER_OBJECT_IN_SESSION);

        if (null == author) {
            newsResult.setSuccessful(false);
            newsResult.setErrorMessage("No user logged in!");

            return SUCCESS;
        }

        try {
            newsSourceService.deleteEntityById(id);

            newsResult.setSuccessful(true);
        } catch (Exception e) {
            logger.error("Exception in delete newsSource with id: " + id, e);
            newsResult.setSuccessful(false);
            newsResult.setErrorMessage(e.getMessage());
        }

        return SUCCESS;
    }

    //test if the news source is valid
    @Action(value = "testNewsSource", results = {@Result(name = SUCCESS, type = "json", params = {"root", "newsResult"})})
    public String testNewsSource() throws Exception {
        newsResult = new GeneralResult();
        Administrator author = (Administrator) session.get(ConstItem.USER_OBJECT_IN_SESSION);

        if (null == author) {
            newsResult.setSuccessful(false);
            newsResult.setErrorMessage("No user logged in!");

            return SUCCESS;
        }

        try {
            NewsSource source = newsSourceService.getNewsSourceById(id);

            String message = newsSourceService.testNewsSource(source);
            newsResult.setServerMessage(message);

            newsResult.setSuccessful(true);
        } catch (Exception e) {
            logger.error("Exception in delete newsSource with id: " + id, e);
            newsResult.setSuccessful(false);
            newsResult.setServerMessage(e.getMessage());
        }

        return SUCCESS;
    }

    @Action(value = "fetchCollectedNews", results = {@Result(name = SUCCESS, type = "json", params = {"root", "dataGridView"})})
    public String fetchCollectedNews() throws Exception {
        List<CollectedNews> collectedNewsList = collectedNewsService.searchCollectedNews(collectedNewsTitle, page, rows);
        int collectedNewsCount = collectedNewsService.countCollectedNews(collectedNewsTitle);

        dataGridView = new HashMap<String, Object>();
        dataGridView.put("rows", collectedNewsList);
        dataGridView.put("total", collectedNewsCount);

        return SUCCESS;
    }

    @Action(value = "convertCollectedNews", results = {@Result(name = SUCCESS, location = "news_form.jsp")})
    public String convertCollectedNews() throws Exception {
        CollectedNews rawNews = collectedNewsService.getCollectedNewsById(id);
        news = new News();
        news.setId(StringUtils.createTimeStamp());
        news.setTitle(rawNews.getTitle());
        news.setSourceUrl(StringUtils.findBaseUrl(rawNews.getSourceLink()));
        news.setContext(rawNews.getBody());
        news.setIntroduction(rawNews.getIntroduction());
        news.setSource(rawNews.getSource());
        news.setCreateDate(new Date());
        news.setPublishDate(new Date());
        Administrator author = (Administrator) session.get(ConstItem.USER_OBJECT_IN_SESSION);
        news.setAuthor(author.getDisplayName());
        news.setCreatorId(author.getId());
        news.setBriefImage(ConstItem.DEFAULT_THUMBNAIL);
        news.setBriefImageVertical(false);

        request.setAttribute("isFromCollected", true);
        request.setAttribute("collectedNewsId", id);
        return SUCCESS;
    }

    //re generate html files for news in last 3 months
    @Action(value = "refreshLatestNews", results = {@Result(name = SUCCESS, type = "json", params = {"root", "newsResult"})})
    public String refreshLatestNews() throws Exception {
        newsResult = new GeneralResult();
        int month = Integer.parseInt(request.getParameter("month"));
        List<String> months = StringUtils.findAdjacentMonths(new Date(),month);
        List<News> newsList = newsService.searchNewsByMonths(months);

        StringBuilder urlPrefixBuilder = fetchUrlPrefixBuilder();
        String baseFolder = ServletActionContext.getServletContext().getRealPath(StringUtils.Persistent_Html_Folder);

        RefreshNewsHtmlThread refreshNewsHtmlThread = new RefreshNewsHtmlThread(baseFolder,
                newsService, newsList, urlPrefixBuilder.toString());
        refreshNewsHtmlThread.start();

        newsResult.setSuccessful(true);
        newsResult.setServerMessage("后台正在更新静态页面，请稍候检查");

        return SUCCESS;
    }

    protected StringBuilder fetchUrlPrefixBuilder() {
        String serverName = request.getServerName();
        int port = request.getServerPort();
        StringBuilder urlPrefixBuilder = new StringBuilder("http://").append(serverName);
        if (port != 80) {
            urlPrefixBuilder.append(":").append(port);
        }

        return urlPrefixBuilder;
    }

    protected String formatNewsContext(String context) {
        if (StringUtils.isNullOrEmpty(context)) {
            return "";
        }

        return StringUtils.replaceWithRegex(NewsService.PageSplitterReg, context, NewsService.PageSplitter);
    }

    protected List<News> findSpecialNews() {
        List<NewsTemplate> templates = new ArrayList<NewsTemplate>();
        NewsColumn specialColumn = columnService.findColumnByName("专题");
        List<NewsColumn> specialColumns = columnService.getAllChildren(specialColumn);
        specialColumns.add(specialColumn);
        templates.add(new NewsTemplate(3, 4));

        return newsService.searchNewsByColumnListAndTemplateList(specialColumns, templates, 2);
    }

    protected String createColumnIdString(List<NewsColumnItem> newsColumnItems) {
        StringBuilder columnIdsBuffer = new StringBuilder("");
        for (NewsColumnItem newsColumnItem : newsColumnItems) {
            columnIdsBuffer.append(newsColumnItem.getColumnId()).append(",");
        }

        if (columnIdsBuffer.length() > 1) {
            columnIdsBuffer.deleteCharAt(columnIdsBuffer.lastIndexOf(","));
        }

        return columnIdsBuffer.toString();
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public Date getPublishFromDate() {
        return publishFromDate;
    }

    public void setPublishFromDate(Date publishFromDate) {
        this.publishFromDate = publishFromDate;
    }

    public Date getPublishToDate() {
        return publishToDate;
    }

    public void setPublishToDate(Date publishToDate) {
        this.publishToDate = publishToDate;
    }

    public NewsService getNewsService() {
        return newsService;
    }

    @Resource(name = "newsService")
    public void setNewsService(NewsService newsService) {
        this.newsService = newsService;
    }

    public String getJsonResult() {
        return jsonResult;
    }

    public void setJsonResult(String jsonResult) {
        this.jsonResult = jsonResult;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public News getNews() {
        return news;
    }

    public void setNews(News news) {
        this.news = news;
    }

    public String getColumns() {
        return columns;
    }

    public void setColumns(String columns) {
        this.columns = columns;
    }

    @Resource(name = "newsColumnItemService")
    public void setNewsColumnItemService(NewsColumnItemService newsColumnItemService) {
        this.newsColumnItemService = newsColumnItemService;
    }

    public String getColumnIds() {
        return columnIds;
    }

    public void setColumnIds(String columnIds) {
        this.columnIds = columnIds;
    }

    public int getTotalNumber() {
        return totalNumber;
    }

    public void setTotalNumber(int totalNumber) {
        this.totalNumber = totalNumber;
    }

    public void setNewsTitle(String newsTitle) {
        this.newsTitle = newsTitle;
    }

    public Map<String, Object> getDataGridView() {
        return dataGridView;
    }

    public void setNewsColumn(String newsColumn) {
        this.newsColumn = newsColumn;
    }

    public void setIdString(String idString) {
        this.idString = idString;
    }

    @Override
    public void setServletRequest(HttpServletRequest httpServletRequest) {
        request = httpServletRequest;
    }

    public void setThumbNailFileName(String thumbNailFileName) {
        this.thumbNailFileName = thumbNailFileName;
    }

    public File getThumbNail() {
        return thumbNail;
    }

    public void setThumbNail(File thumbNail) {
        this.thumbNail = thumbNail;
    }

    public boolean isOperationSuccess() {
        return operationSuccess;
    }

    public List<UrlKeyword> getKeywords() {
        return keywords;
    }

    public String getTag() {
        return tag;
    }

    public void setTag(String keyword) {
        this.tag = keyword;
    }

    public Photo getPhoto() {
        return photo;
    }

    public GeneralResult getNewsResult() {
        return newsResult;
    }

    public ColumnService getColumnService() {
        return columnService;
    }

    @Resource(name = "columnService")
    public void setColumnService(ColumnService columnService) {
        this.columnService = columnService;
    }

    @Resource(name = "videoService")
    public void setVideoService(VideoService videoService) {
        this.videoService = videoService;
    }

    @Resource(name = "inLineWordService")
    public void setInLineWordService(InLineWordService inLineWordService) {
        this.inLineWordService = inLineWordService;
    }

    @Resource(name = "newsSourceService")
    public void setNewsSourceService(NewsSourceService newsSourceService) {
        this.newsSourceService = newsSourceService;
    }

    @Override
    public void setSession(Map<String, Object> session) {
        this.session = session;
    }

    public int getIndexLevel() {
        return indexLevel;
    }

    public void setIndexLevel(int indexLevel) {
        this.indexLevel = indexLevel;
    }

    public int getInIndex() {
        return inIndex;
    }

    public void setInIndex(int inIndex) {
        this.inIndex = inIndex;
    }

    public String getColumnUrl() {
        return columnUrl;
    }

    public void setColumnUrl(String columnUrl) {
        this.columnUrl = columnUrl;
    }

    public void setTopColumnUrl(String topColumnUrl) {
        this.topColumnUrl = topColumnUrl;
    }

    public String getNewsIndexTitle() {
        return newsIndexTitle;
    }

    public void setNewsIndexTitle(String newsIndexTitle) {
        this.newsIndexTitle = newsIndexTitle;
    }

    public InLineWord getInLineWordForm() {
        return inLineWordForm;
    }

    public void setInLineWordForm(InLineWord inLineWordForm) {
        this.inLineWordForm = inLineWordForm;
    }

    public List<InLineWord> getInLineWords() {
        return inLineWords;
    }

    public void setInLineWords(List<InLineWord> inLineWords) {
        this.inLineWords = inLineWords;
    }

    public InLineWordResult getInLineWordResult() {
        return inLineWordResult;
    }

    public void setInLineWordResult(InLineWordResult inLineWordResult) {
        this.inLineWordResult = inLineWordResult;
    }

    public String getWordName() {
        return wordName;
    }

    public void setWordName(String wordName) {
        this.wordName = wordName;
    }

    public String getNewsSourceTitle() {
        return newsSourceTitle;
    }

    public void setNewsSourceTitle(String newsSourceTitle) {
        this.newsSourceTitle = newsSourceTitle;
    }

    public NewsSource getNewsSource() {
        return newsSource;
    }

    public void setNewsSource(NewsSource newsSource) {
        this.newsSource = newsSource;
    }

    public void setCollectedNewsService(CollectedNewsService collectedNewsService) {
        this.collectedNewsService = collectedNewsService;
    }

    public String getCollectedNewsTitle() {
        return collectedNewsTitle;
    }

    public void setCollectedNewsTitle(String collectedNewsTitle) {
        this.collectedNewsTitle = collectedNewsTitle;
    }
}

